package com.hanbang.mrcm.photo;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.RelativeLayout;

/*
 * 照片裁剪的复合控件
 */
public class ClipLayout extends RelativeLayout {

	private ClipZoomView zoomView;
	private ClipBorderView borderView;
	private Context context = null;
	public static final int ROUND = 1;
	public static final int RECT = 2;
	/**
	 * 照片裁剪的边框距离边缘的宽度（dp）默认=20
	 */
	private int clipPadding = 20;
	/*
	 * 边框的颜色 默认为白色
	 */
	private int borderColor = 0xffffff;
	/*
	 * 边框宽度
	 */
	private float borderWidth = 1;
	/*
	 * 边框形状 现在支持矩形和圆形 (默认圆形)
	 */
	private int borderShape = ROUND;

	private Bitmap bitmap = null;

	public ClipLayout(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
	}

	public void setClipPhoto(Bitmap bitmap) {
		this.bitmap = bitmap;
	}

	public void setClipPadding(int clipPadding) {
		this.clipPadding = dpToPx(clipPadding);
	}

	public void setBorderColor(int borderColor) {
		this.borderColor = borderColor;
	}

	public void setBorderShape(int borderShape) {
		this.borderShape = borderShape;
	}

	public void setBorderWidth(float borderWidth) {
		this.borderWidth = dpToPx(borderWidth);
	}

	public void show() {
		if (zoomView == null || borderView == null) {
			zoomView = new ClipZoomView(context);
			borderView = new ClipBorderView(context);
			android.view.ViewGroup.LayoutParams lp = new LayoutParams(
					android.view.ViewGroup.LayoutParams.MATCH_PARENT,
					android.view.ViewGroup.LayoutParams.MATCH_PARENT);
			android.view.ViewGroup.LayoutParams lp2 = new LayoutParams(
					android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
					android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
			this.addView(zoomView, lp);
			this.addView(borderView, lp2);
		}
		zoomView.setImageBitmap(bitmap);
		zoomView.setHorizontalPadding(this.clipPadding);
		borderView.setHorizontalPadding(this.clipPadding);
		borderView.setBorderColor(borderColor);
		borderView.setBorderShape(borderShape);
		borderView.setBorderWidth(this.borderWidth);
		zoomView.invalidate();
		borderView.invalidate();
		invalidate();
	}

	/*
	 * 裁切图片q
	 */
	public Bitmap clip() {
		return zoomView.clip();
	}

	/*
	 * dp转px
	 */
	private int dpToPx(float dp) {
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
				getResources().getDisplayMetrics());
	}
}
